#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@author: yuejl
@application:
@contact: lewyuejian@163.com
@file: parser.py
@time: 2021/8/22 0022 18:17
@desc: 数据解析器
'''
from common import BASE_PATH

from common import exceptions
from common.compat_format import _sort_testcase_dict_by_custom_order, _sort_teststep_dict_by_custom_order
from typing import Dict, List, Text, Union, Any

import re
absolute_http_url_regexp = re.compile(r"^https?:/{2}\w.+$", re.I)

def get_mapping_variable(variable_name: Text, variables_mapping: Dict[Text, Any]):
    try:
        return variables_mapping[variable_name]
    except KeyError:
        raise exceptions.VariableNotFound(
            f"{variable_name} not found in {variables_mapping}"
        )

def parser_test_step_data(variable_name: Text, variables_mapping: Dict[Text, Any]):
    """解析yaml数据，将yaml数据拆分成测试用例数据
    >>>
    {
        case_id,
        child_title,
        url,
        method,
        headers,
        tips,
        priority,
        ids,
        child_info,
        json,
        except_code,
        except_msg
    }
    :param variables:
    :return:
    """
    test_case_list: List[Dict] = []
    test_step:Dict = {}
    test_data = get_mapping_variable(variable_name, variables_mapping)

    test_step["url"] = test_data.get("url")
    test_step["method"] = test_data.get("method")
    test_step["headers"] = test_data.get("headers")
    test_step["tips"] = test_data.get("tips")
    test_step["ids"] = test_data.get("ids")

    for step in test_data.get("request"):
        test_step.update(step)
        test_case_list.append(_sort_testcase_dict_by_custom_order(test_step))

    return test_case_list

def build_url(base_url, path):
    """
    prepend url with base_url unless it's already an absolute URL
    在 url 前面加上 base_url 除非它已经是绝对 URL

    Args:
        raw_string (str): string content 字符串内容

    Returns:
        str: Spliced into absolute url
        字符串：拼接成绝对url

    Examples:

        base_url = 'http://www.baidu.com/'
        path = 'http://www.baidu.com/sasssss'

        >>> build_url(base_url,path)
        http://www.baidu.com/sasssss

        base_url = 'http://www.baidu.com/'
        path = '/sss'
        >>> build_url(base_url,path)
        http://www.baidu.com/sss
    """
    if absolute_http_url_regexp.match(path):
        return path
    elif base_url:
        return "{}/{}".format(base_url.rstrip("/"), path.lstrip("/"))
    else:
        raise print("base url missed!")

